package com.google.code.biglo.runtime.flownode;

import java.util.Date;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.Validate;

import com.google.code.biglo.dao.ActivityDao;
import com.google.code.biglo.dao.ActivityState;
import com.google.code.biglo.lang.bpmn.model.TEndEvent;
import com.google.code.biglo.lang.bpmn.model.TFlowNode;
import com.google.code.biglo.lang.bpmn.model.TScriptTask;
import com.google.code.biglo.lang.bpmn.model.TStartEvent;
import com.google.code.biglo.lang.bpmn.model.TTerminateEventDefinition;
import com.google.code.biglo.runtime.BpmnInstance;

public abstract class FlowNode {
	protected ActivityDao dao;
	protected TFlowNode tFlowNode;
	protected BpmnInstance instance;
	protected Date executionDate;
	
	public static FlowNode create(ActivityDao dao, TFlowNode tFlowNode, BpmnInstance instance) {
		FlowNode node = createClass(tFlowNode);
		node.dao = dao;
		node.tFlowNode = tFlowNode;
		node.instance = instance;
		return node;
	}
	
	private static FlowNode createClass(TFlowNode tFlowNode) {
		if (tFlowNode instanceof TScriptTask) {
			return new ScriptTask();
		} else if (tFlowNode instanceof TStartEvent) {
			return new StartEvent();
		} else if (tFlowNode instanceof TEndEvent) {
			return new EndEvent();
		} else {
			throw new NotImplementedException(tFlowNode.toString());
		}
	}
	
	public void setExecutionDate(Date executionDate) {
		this.executionDate = executionDate;
	}

	public void activate() {
		Validate.isTrue(dao.getState() == ActivityState.ENABLED);
		dao.setState(ActivityState.ACTIVE);
	}
	
	public void completing() {
		Validate.isTrue(dao.getState() == ActivityState.ACTIVE);
		dao.setState(ActivityState.COMPLETING);
	}
}
